package com.coder.rental.security;

import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.service.IPermissionService;
import com.coder.rental.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 客户端用户详情服务类，实现Spring Security的UserDetailsService接口
 * 用于根据用户名加载用户详细信息
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private IUserService userService;
    @Resource
    private IPermissionService permissionService;
    /**
     * 根据用户名加载用户详细信息
     * @param username 用户名
     * @return UserDetails 用户详细信息对象
     * @throws UsernameNotFoundException 当用户不存在时抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        User user=userService.selectByUsername(username);
        // 如果用户不存在，抛出用户名未找到异常
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询用户权限表
        List<Permission> permissions=permissionService.selectPermissionListByUserId(user.getId());
        user.setPermissionList( permissions);
        List<String> list=permissions.stream().filter(Objects::nonNull).map(Permission::getPermissionCode).filter(Objects::nonNull).toList();
        String[] array=list.toArray(new String[list.size()]);
        List<GrantedAuthority> authorityList= AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorityList);
        return user;
    }
}

